package com.fac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fac.constant.EquipmentStatus;
import com.fac.constant.ExceptionConstant;
import com.fac.constant.CommonConstant;
import com.fac.dto.EquipmentAvailableQueryDTO;
import com.fac.dto.EquipmentCreateDTO;
import com.fac.dto.EquipmentPageQueryDTO;
import com.fac.dto.EquipmentUpdateDTO;
import com.fac.entity.Equipment;
import com.fac.entity.EquipmentCategory;
import com.fac.exception.BusinessException;
import com.fac.mapper.EquipmentCategoryMapper;
import com.fac.mapper.EquipmentMapper;
import com.fac.result.PageResult;
import com.fac.service.EquipmentService;
import com.fac.vo.EquipmentAvailableVO;
import com.fac.vo.EquipmentVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备服务实现类
 */
@Service
@Slf4j
public class EquipmentServiceImpl implements EquipmentService {

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private EquipmentCategoryMapper equipmentCategoryMapper;

    /**
     * 创建设备
     *
     * @param equipmentCreateDTO 设备创建DTO
     * @return 创建的设备VO
     */
    @Override
    public EquipmentVO create(EquipmentCreateDTO equipmentCreateDTO) {
        log.info("创建设备：{}", equipmentCreateDTO);

        // 检查设备编码是否已存在
        LambdaQueryWrapper<Equipment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Equipment::getCode, equipmentCreateDTO.getCode());
        if (equipmentMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(ExceptionConstant.EQUIPMENT_CODE_EXISTS);
        }

        // 检查分类是否存在且启用
        EquipmentCategory category = equipmentCategoryMapper.selectById(equipmentCreateDTO.getCategoryId());
        if (category == null) {
            throw new BusinessException(ExceptionConstant.PARENT_CATEGORY_NOT_FOUND);
        }
        if (category.getStatus() == CommonConstant.STATUS_DISABLE) {
            throw new BusinessException(ExceptionConstant.CATEGORY_DISABLED);
        }

        // 创建设备实体
        Equipment equipment = new Equipment();
        BeanUtils.copyProperties(equipmentCreateDTO, equipment);

        // 设置初始状态为闲置
        equipment.setStatus(EquipmentStatus.IDLE);

        // 保存设备
        equipmentMapper.insert(equipment);

        // 转换为VO
        EquipmentVO equipmentVO = EquipmentVO.builder()
                .equipmentId(equipment.getEquipmentId())
                .code(equipment.getCode())
                .name(equipment.getName())
                .categoryName(category.getName())
                .brand(equipment.getBrand())
                .model(equipment.getModel())
                .status(equipment.getStatus())
                .value(equipment.getValue())
                .location(equipment.getLocation())
                .specifications(equipment.getSpecifications())
                .purchaseDate(equipment.getPurchaseDate())
                .warrantyPeriod(equipment.getWarrantyPeriod())
                .build();

        return equipmentVO;
    }

    /**
     * 分页查询设备
     *
     * @param dto 分页查询条件
     * @return 分页结果
     */
    @Override
    public PageResult pageQuery(EquipmentPageQueryDTO dto) {
        log.info("分页查询设备：{}", dto);

        // 构建查询条件
        LambdaQueryWrapper<Equipment> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加关键字查询条件
        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            queryWrapper.like(Equipment::getName, dto.getKeyword())
                    .or()
                    .like(Equipment::getCode, dto.getKeyword());
        }

        // 添加分类查询条件
        if (dto.getCategoryId() != null) {
            queryWrapper.eq(Equipment::getCategoryId, dto.getCategoryId());
        }

        // 添加状态查询条件
        if (dto.getStatus() != null) {
            queryWrapper.eq(Equipment::getStatus, dto.getStatus());
        }

        // 创建分页对象
        Page<Equipment> page = new Page<>(dto.getPage(), dto.getSize());

        // 执行分页查询
        Page<Equipment> equipmentPage = equipmentMapper.selectPage(page, queryWrapper);

        // 转换为VO列表
        List<EquipmentVO> voList = equipmentPage.getRecords().stream()
                .map(equipment -> {
                    EquipmentVO vo = new EquipmentVO();
                    BeanUtils.copyProperties(equipment, vo);

                    // 查询分类名称
                    EquipmentCategory category = equipmentCategoryMapper.selectById(equipment.getCategoryId());
                    vo.setCategoryName(category != null ? category.getName() : null);

                    return vo;
                })
                .collect(Collectors.toList());

        return new PageResult(equipmentPage.getTotal(), voList);
    }

    /**
     * 更新设备
     *
     * @param equipmentId 设备ID
     * @param equipmentUpdateDTO 设备更新DTO
     * @return 更新后的设备VO
     */
    @Override
    public EquipmentVO update(Long equipmentId, EquipmentUpdateDTO equipmentUpdateDTO) {
        log.info("更新设备，ID：{}，更新内容：{}", equipmentId, equipmentUpdateDTO);

        // 设置设备ID
        equipmentUpdateDTO.setEquipmentId(equipmentId);

        // 创建设备实体
        Equipment equipment = new Equipment();
        BeanUtils.copyProperties(equipmentUpdateDTO, equipment);

        // 更新设备
        equipmentMapper.updateById(equipment);

        // 查询更新后的设备
        equipment = equipmentMapper.selectById(equipmentId);

        // 转换为VO
        return EquipmentVO.builder()
                .equipmentId(equipment.getEquipmentId())
                .name(equipment.getName())
                .location(equipment.getLocation())
                .status(equipment.getStatus())
                .build();
    }

    @Override
    public PageResult listAvailable(EquipmentAvailableQueryDTO queryDTO) {
        log.info("查询可租赁设备列表：{}", queryDTO);

        // 构建查询条件
        LambdaQueryWrapper<Equipment> queryWrapper = new LambdaQueryWrapper<>();
        
        // 只查询闲置状态的设备
        queryWrapper.eq(Equipment::getStatus, EquipmentStatus.IDLE);

        // 添加分类查询条件
        if (queryDTO.getCategoryId() != null) {
            queryWrapper.eq(Equipment::getCategoryId, queryDTO.getCategoryId());
        }

        // 创建分页对象
        Page<Equipment> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());

        // 执行分页查询
        Page<Equipment> equipmentPage = equipmentMapper.selectPage(page, queryWrapper);

        // 转换为VO列表
        List<EquipmentAvailableVO> voList = equipmentPage.getRecords().stream()
                .map(equipment -> {
                    // 查询分类名称
                    EquipmentCategory category = equipmentCategoryMapper.selectById(equipment.getCategoryId());

                    return EquipmentAvailableVO.builder()
                            .equipmentId(equipment.getEquipmentId())
                            .code(equipment.getCode())
                            .name(equipment.getName())
                            .categoryName(category != null ? category.getName() : null)
                            .brand(equipment.getBrand())
                            .specifications(equipment.getSpecifications())
                            .location(equipment.getLocation())
                            .build();
                })
                .collect(Collectors.toList());

        return new PageResult(equipmentPage.getTotal(), voList);
    }
}
